import os
import cv2
from PIL import Image

def create_video_from_tif(input_dir, output_path, fps=60):
    """
    将目录下的tif图片序列转换为视频
    
    参数:
        input_dir: 输入目录路径
        output_path: 输出视频路径
        fps: 视频帧率(默认3.32fps，使199帧视频时长约为1分钟)
    """
    # 获取目录下所有tif文件并按名称排序
    tif_files = sorted([f for f in os.listdir(input_dir) if f.endswith('.tif')])
    
    if not tif_files:
        print("未找到tif文件")
        return
    
    # 读取第一张图片获取尺寸信息
    first_img = Image.open(os.path.join(input_dir, tif_files[0]))
    width, height = first_img.size
    
    # 创建视频写入器
    fourcc = cv2.VideoWriter_fourcc(*'mp4v')  # type: ignore
    video_writer = cv2.VideoWriter(output_path, fourcc, fps, (width, height))
    
    # 逐帧处理并写入视频
    for tif_file in tif_files:
        img_path = os.path.join(input_dir, tif_file)
        
        # 使用Pillow读取tif并转换为OpenCV格式
        pil_img = Image.open(img_path)
        cv_img = cv2.cvtColor(np.array(pil_img), cv2.COLOR_RGB2BGR)
        
        video_writer.write(cv_img)
        print(f"已处理: {tif_file}")
    
    video_writer.release()
    print(f"视频已生成: {output_path}")

if __name__ == "__main__":
    input_dir = "J:/test/C001H001S0001"  # 输入目录
    output_path = "output.mp4"  # 输出视频路径
    
    # 检查并安装必要库
    try:
        import numpy as np
    except ImportError:
        print("正在安装numpy...")
        os.system("python -m pip install numpy")
        import numpy as np
    
    try:
        from PIL import Image
    except ImportError:
        print("正在安装Pillow...")
        os.system("python -m pip install pillow")
        from PIL import Image
    
    try:
        import cv2
    except ImportError:
        print("正在安装opencv-python...")
        os.system("python -m pip install opencv-python")
        import cv2
    
    create_video_from_tif(input_dir, output_path)
